package com.richapp.launcher.serialport.gateway.command;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jack.util.string.StringUtil;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelHistoryDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.message.MsgConstant;
import com.richapp.launcher.net.mobile.message.DeviceStatusReply;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.scene.SceneServer;
import com.richapp.launcher.serialport.gateway.ControlInstructionMessage;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.launcher.serialport.gateway.GatewayServer;

public class ControlDeviceCmd extends BasicCommand {

	private static ControlDeviceCmd controlDeviceCmd = null;
	private String mClientId="";
	private ControlDeviceCmd() {
		
	}
	
	public static ControlDeviceCmd getInstance(){
		if(controlDeviceCmd == null){
			controlDeviceCmd = new ControlDeviceCmd();
		}
		return controlDeviceCmd;
	}
	
	/**
	 * 打开设备
	 */
	public void openDevice( String cpuBoxId,String deviceId, String deviceNumber,String way) {
		this.ID = deviceId;
		this.Number = deviceNumber;
		this.Switch = "FF";
		this.Way = way;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationCMD());
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_OPEN_ONE);
		GatewayServer.getInstance().writeMessage(cim);

	}


	/**
	 * 打开设备用于手机端操作设备时候不需要同步状态到当前操作的客户端
	 */
	public void openDeviceTackClientId(String clientId, String cpuBoxId,String deviceId, String deviceNumber,String way) {
		mClientId=clientId;
		this.ID = deviceId;
		this.Number = deviceNumber;
		this.Switch = "FF";
		this.Way = way;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationCMD());
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_OPEN_ONE);
		GatewayServer.getInstance().writeMessage(cim);

	}


	/**
	 * 关闭设备用于手机端操作设备时候不需要同步状态到当前操作的客户端
	 */
	public void closeDeviceTackClientId(String clientId, String cpuBoxId,String deviceId, String deviceNumber,String way) {
		mClientId=clientId;
		this.ID = deviceId;
		this.Number = deviceNumber;
		this.Switch = "00";
		this.Way = way;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationCMD());
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_CLOSE_ONE);
		GatewayServer.getInstance().writeMessage(cim);
	}

	/**
	 * 全开
	 */
	public void openAllDevice() {
		ControlInstructionMessage cim = new ControlInstructionMessage(null,null,null,null);
		cim.setHexInstruction(GatewaytConstant.INSTRUCTION_BROADCAST_OPEN_ALL_LIGHT_str);
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_OPEN_ALL);
		GatewayServer.getInstance().writeMessage(cim);
	}

	/**
	 * 全关
	 */
	public void closeAllDevice() {
		ControlInstructionMessage cim = new ControlInstructionMessage(null,null,null,null);
		cim.setHexInstruction(GatewaytConstant.INSTRUCTION_BROADCAST_CLOSE_ALL_LIGHT_STR);
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_CLOSE_ALL);
		GatewayServer.getInstance().writeMessage(cim);
	}

	/**
	 * 调光灯增亮/窗帘盒正转设置
	 */
	public void setDimming(String cpuBoxId,String deviceId, String deviceNumber, String Brightness,String way) {
		this.ID = deviceId;
		this.Number = deviceNumber;
		this.Switch = Brightness;
        this.Way = way;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationCMD());
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_SWITCH);
		GatewayServer.getInstance().writeMessage(cim);
	}


	/**
	 * 停止设备 适用于调光灯，窗帘等设备
	 */
	public void stopDevice(String cpuBoxId,String deviceId, String deviceNumber,String way) {
		this.ID = deviceId;
		this.Number = deviceNumber;
		this.Switch = "3F";
        this.Way = way;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationCMD());
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_STOP);
		GatewayServer.getInstance().writeMessage(cim);
	}

	/**
	 * 关闭设备
	 */
	public void closeDevice(String cpuBoxId,String deviceId, String deviceNumber,String way) {
		this.ID = deviceId;
		this.Number = deviceNumber;
		this.Switch = "00";
        this.Way = way;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationCMD());
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_CLOSE_ONE);
		GatewayServer.getInstance().writeMessage(cim);
	}

	/**
	 * 上行指令解析
	 * @param hexData
	 */
	@Override
	public void analyticalCmd(String hexData) {
		String deviceId = hexData.substring(8, 10);
		String deviceNumber = hexData.substring(10, 12);
		String way = hexData.substring(12, 14);
		String deviceStatus = hexData.substring(14, 16);
		String onlineStatus = hexData.substring(18, 20);
		String signal = hexData.substring(22, 24);

		String way2 = null;
		String deviceStatus2 = null;

		String ifAnyone = "false";

		if(GatewaytConstant.getDeviceTypeMap().containsKey(deviceId)){


			if(GatewaytConstant.getMiltiWayMap().containsKey(deviceId)){
				//普通灯控模块
				ifAnyone = hexData.substring(20, 22);

				if(GatewaytConstant.ID_TYPE_ONE_CASE_DIMMING_SWITCH_STR.equals(deviceId)){	//1路调光


				}else if(GatewaytConstant.ID_TYPE_TWO_CASE_DIMMING_SWITCH_STR.equals(deviceId)){	//2路调光
					way2 = hexData.substring(24, 26);
					deviceStatus2 = hexData.substring(26, 28);
				}
			}

			BoxModelDao bmd = new BoxModelDao(GatewayServer.getInstance().getContext());
			BoxModel bm = bmd.getCurrentBox();
			DeviceModelDao dmd = new DeviceModelDao(GatewayServer.getInstance().getContext());
			List<DeviceModel> list = new ArrayList<DeviceModel>();

			DeviceModel dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, deviceNumber, way);
			DeviceModel dm2 = null;

			if(dm != null){
				dm.setOnlineStatus(onlineStatus);
				dm.setDeviceStatus(deviceStatus);
				dm.setSignal(signal);
				dm.setIfAnyone(ifAnyone);
				
				dmd.add(dm);
				dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, deviceNumber, way);
				
				//统计电量
				new DeviceModelHistoryDao(GatewayServer.getInstance().getContext()).addModelHisotry(dm);;

				list.add(dm);
			}

			if(!StringUtil.isNullOrEmpty(way2)){
				dm2 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, deviceNumber, way2);
				if(dm2 != null){
					dm2.setOnlineStatus(onlineStatus);
					dm2.setDeviceStatus(deviceStatus2);
					dm2.setSignal(signal);
					dm2.setIfAnyone(ifAnyone);

					dmd.add(dm2);
					dm2 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, deviceNumber, way2);

					//统计电量
					new DeviceModelHistoryDao(GatewayServer.getInstance().getContext()).addModelHisotry(dm2);

					list.add(dm2);
				}
			}

			updateData(list);
		}
	}

	private  void updateData(List<DeviceModel> list){
		//发送消息到客户端同步
		DeviceStatusReply deviceStatusReply = new DeviceStatusReply();
		deviceStatusReply.setUserName(new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox().getUserName());
		deviceStatusReply.setCurrentBoxCpuId(new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox().getBoxCpuId());
		deviceStatusReply.setDeviceStatus(list);

		JSONObject jsonObject = (JSONObject)JSON.toJSON(deviceStatusReply);

		//发送所有当前手机
		if (!mClientId.equals("")){
			UserServer.getInstance().sendAllUsersMessageExcept(mClientId,jsonObject.toJSONString());
		}else {
			UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());
		}
		if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
			jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
			//发送服务器
			RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
			//发送其他机顶盒
			BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
		}
	}

}
